﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeTop.复习九月份
{
    public class Solution150
    {
        public int EvalRPN(string[] tokens)
        {
            int len = tokens.Length;
            Stack<int> stack = new Stack<int>();

            for (int i = 0; i < len; i++)
            {
                string token = tokens[i];
                if (token == "+" || token == "-" || token == "*" || token == "/")
                {
                    int a = stack.Pop();//后操作数
                    int b = stack.Pop();
                    int num = Cal(token, b, a);
                    stack.Push(num);
                }
                else
                {
                    int num = StrToNum(token);
                    stack.Push(num);
                }
                MyPrintStack(stack);
            }
            return stack.Pop();
        }

        private void MyPrintStack(Stack<int> stack)
        {
            int[] nums = stack.ToArray();
            Array.Reverse(nums);

            for (int i = 0; i < nums.Length; i++)
            {
                Console.Write(nums[i] + ",");
            }
            Console.WriteLine();
        }

        private int Cal(string token, int a, int b)
        {
            if (token == "+")
            {
                return a + b;
            }
            else
            if (token == "-")
            {
                return a - b;
            }
            else
            if (token == "*")
            {
                return a * b;
            }
            else
            {
                return a / b;
            }
        }

        private int StrToNum(string s)//有负数
        {
            int flag = 1; int res = 0;
            if (s[0] == '-')
            {
                flag = -1;
            }
            else
            {
                res = s[0] - '0';
            }

            for (int i = 1; i < s.Length; i++)
            {
                int num = s[i] - '0';
                res = res * 10 + num;
            }

            return res * flag;
        }
    }

    internal class Program150
    {
        private static void Main150(string[] args)
        {
            //string[] tokens = ["2", "1", "+", "3", "*"];
            string[] tokens = ["4", "13", "5", "/", "+"];
            Solution150 solution = new Solution150();
            int res = solution.EvalRPN(tokens);
            Console.WriteLine(res);
        }
    }
}